package com.zky.gulimall.search.Service.Impl;

import com.alibaba.fastjson.JSON;
import com.zky.common.to.es.SkuEsModel;
import com.zky.gulimall.search.Service.ProductSaveService;
import com.zky.gulimall.search.constant.EsConstant;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

import static com.zky.gulimall.search.config.ElasticSearchConfig.COMMOM_OPTIONS;

/**
 * @Description 实现类
 * @Author 张开源
 * @Date 2022/10/17 20:38
 * @Version 1.0
 **/
@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {
    @Resource
    private RestHighLevelClient restHighLevelClient;
    @Override
    public Boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {

        //给es建立索引
        log.info("skuEsModels:"+JSON.toJSONString(skuEsModels));
        if(CollectionUtils.isEmpty(skuEsModels)){
            return false;
        }
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            indexRequest.source(JSON.toJSONString(skuEsModel), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, COMMOM_OPTIONS);
        if(bulk.hasFailures()){
            log.error("bulk has fail");
        }
        return bulk.hasFailures();

    }
}
